import datetime
import json
import traceback

from flow_alchemy.util.serializable import Serializable


class ModelEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, str):
            return obj
        elif isinstance(obj, int):
            return obj
        elif isinstance(obj, float):
            return obj
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S.%f')
        elif isinstance(obj, datetime.date):
            return obj.strftime('%Y-%m-%d')
        elif isinstance(obj, datetime.time):
            return obj.isoformat()
        elif isinstance(obj, dict):
            result = {}
            for k in obj:
                result[k] = self.default(obj[k])
            return result
        elif isinstance(obj, list):
            return [ self.default(_) for _ in obj]
        elif isinstance(obj, Serializable):
            return self.default(obj.to_dict())
        elif isinstance(obj, Exception):
            return traceback.format_exc()
        print(obj)
        return json.JSONEncoder.default(self, obj)